//库命名空间
var QF = {
	'version':'1.0.0'
};
(function(ns){
	/**
	 * 吸顶插件
	 * @type {Class}
	 */
	ns.SideByTop = new Class({
		Implements:[Options, Events],
		options:{
			'class': 'clonediv'
		},
		/**
		 * 初始化
		 * @param el 某个容器(Element or element id)
		 * @param options 需要覆盖的属性
		 */
		initialize: function(options){
			this.setOptions(options);
			var ops = this.options;
			this.handle = new Element('div', {'class': ops['class']})
					.inject($(document.body))
					.setStyles({
						'position': this.isSurpportFixed() ? 'fixed' : 'absolute',
						'display': 'none',
						'top': 0,
						'width':'100%',
						'z-index':65535
					});
			this.bounds = {
				scroll: this.scroll.bind(this)
			};
			this.attach();
		},

		/**
		 * 侦听滚动条事件
		 */
		scroll: function(){
			var hd = this.handle;
			var top =  window.getScroll().y;
			//console.log('scroll',top);
			if(top > 110){
				hd.setStyle('display','block');
			}else{
				hd.setStyle('display','none');
			}
			if(this.isSurpportFixed()) return;
			hd.setStyle('top', top);
		},
		/**
		 * 事件
		 */
		attach: function(){
			window.addEvent('scroll', this.bounds.scroll);
		},

		/**
		 * 是否支持固定浏览器某位置
		 * @returns {boolean}
		 */
		isSurpportFixed: function(){
			//如果需要测试滑动效果，用IE6或者打开下一句注释
			 return false;
			// return !window.ie6;
		},

		/**
		 * 复制某个容器的内容到当前容器下
		 * @param el 容器ID
		 */
		clone: function(el){
			this.handle.set('html', $(el).get('html'));
			return this;
		}
	});

    /**
     * 用于不支持fixed的浏览器
     * 目前只支持垂直方向
     * @type {Class}
     */
    ns.SideBy = new Class({
        Implements:[Options, Events],
        options:{
            'property':'top',//需要固定位置的样式属性
            'value': 0//需要停靠的值
        },
        /**
         * 初始化
         * @param el 某个容器(Element or element id)
         * @param options 需要覆盖的属性
         */
        initialize: function(el, options){
            this.setOptions(options);
            var ops = this.options;
            var hd = this.handle = document.id(el).setStyle('position',this.isSurpportFixed() ? 'fixed' : 'absolute');
            hd.style[ops.property] = ops.value + 'px';
            this.bounds = {
                scroll: this.scroll.bind(this)
            };

            this.attach();
        },
        /**
         * 侦听滚动条事件
         */
        scroll: function(){
            var ops = this.options;
            this.handle.setStyle(ops.property,ops.value + window.getScroll().y);
        },
        /**
         * 事件
         */
        attach: function(){
            if(this.isSurpportFixed()) return;
            window.addEvent('scroll', this.bounds.scroll);
        },

        /**
         * 是否支持固定浏览器某位置
         * @returns {boolean}
         */
        isSurpportFixed: function(){
            //如果需要测试滑动效果，用IE6或者打开下一句注释
			//return false;
            return !window.ie6;
        }
    });
    /**
     * 滑动
     * @type {Class}
     */
    ns.Slide = new Class({
        Implements:[Options, Events],
        options: {
            'mode': 1,//默认打开还是关闭（0 关闭 1 打开）
            'width': 130,
            'handle': null//触发滑动的元素，不传入则在容器上触发（句柄Element或者ID）
        },
        /**
         * 初始化
         * @param el 容器Elmenet或者容器ID
         * @param viewEL 需要改变宽度的容器ID
         * @param options 需要覆盖的参数
         */
        initialize: function(el, viewEL, options){
            this.setOptions(options);
            var ops = this.options;
            var con = this.container = $(el);
            this.handle = ops.handle ? con.getElement(ops.handle) : con;
            this.mode = ops.mode;
            this.viewEL = $(viewEL);
            this.bounds = {
                expand: this.expand.bind(this),
                contract: this.contract.bind(this)
            }
            this.attach();
        },

        attach: function(){
            var bounds = this.bounds;
            this.handle.addEvent('mouseenter', bounds.expand);
            this.container.addEvent('mouseleave', bounds.contract);
        },

        expand: function(){
            if(this.mode == 1) return;
            var ops = this.options;
            this.mode = 1;
            this.viewEL.get('tween').start('width', ops['width']);
            this.fireEvent('expand');
        },

        contract: function(){
            var ops = this.options;
            this.mode = 0;
            this.viewEL.get('tween').start('width', 0);
            this.fireEvent('contract');
        }
    });
	
	//hover加状态用法
	/*===========================================================
		var a = new QF.fn($$("element",{'hoverClass':'hover'}));
	============================================================*/
	ns.ToggleClass = new Class({
		Implements:[Options,Events],
		options:{
			'hoverClass':'hover'//默认属性
		},
		initialize: function(el,options){
			this.container = $$(el);
			var ops = this.options;
			this.settings = ops['hoverClass'];
			this.fnClassToggle();
		},
		fnClassToggle:function(){
			if (this.container.length < 0) return false; 
			var cl = this.settings;
			if(this.container.length > 0){
				this.container.each(function(item,index){
					item.addEvent("mouseenter",function(){
						this.addClass(cl);
					});
					item.addEvent("mouseleave",function(){
						this.removeClass(cl);
					})
				})
			}
		}
	});	

	
	/*分类弹出*/
	ns.qfcatShow = new Class({
		Implements: [Options, Events],
		options:{
			'container':'categorys',//主容器
			'menuItem':'.item',//菜单项的CSS名称
			'subContainer': '.dorpdown-layer',//子菜单容器的css名称，如果是用的ID，可以填（#id）
			'subMenuPrefix':'category-item-'//子菜单项ID前缀
		},	
		initialize: function(options){
			this.setOptions(options);
			var ops = this.options;
			var hd = this.handle = document.id(ops['container']);
			this.lastItem = null;
			this.items = hd.getElements(ops['menuItem']);
			this.subContainer = hd.getElement(ops['subContainer']);
			this.subConTop = parseInt(this.subContainer.getStyle('top'));
			this.top = hd.getCoordinates().top;
			this.bounds = {
				'leave': this.leave.bind(this),
				'over': this.over.bind(this)
			}	
			this.attach();
		},	
		attach: function(){
			this.handle.addEvent('mouseleave', this.bounds.leave);
			this.items.each(function(item){
				this.hideSub(item);
				item.addEvent('mouseenter',this.bounds.over);
			},this);
		},
		over: function(el){
			this.leave();
			this.showSub(el.target);
		},
		showSub:function(item){
			var id = item.get('data-index');
			var subId = this.options['subMenuPrefix'] + id;
			var sub = document.id(subId);
			if(!sub) return;
			var subCon = this.subContainer;
			sub.setStyle('display','block');
			if(subCon){
				subCon.setStyle('display','block');
				var itemBottom = item.getCoordinates().bottom;
				var subHeight = sub.getCoordinates().height;	
				var scrollTop = document.body.scrollTop;
				var subTop = this.subConTop;
				//如果出现了滚动条
				//如果滚动条的高度已经超过了基准线
				if(scrollTop >= this.top + this.subConTop){
					subTop = scrollTop - this.top;
				}	
				//先判断当前的高度加上容器的高度是否超过了当前Item的底部，如果不到底部，优先底部对齐
				if(itemBottom - Math.max(scrollTop, this.top + this.subConTop) > subHeight) {
					subTop = itemBottom - this.top - subHeight - parseInt(subCon.getStyle('border'));
				}
				subCon.setStyle('top',subTop);
			}
			this.lastItem = item;
			this.fireEvent('over', item);
		},	
		leave: function(){
			var lastItem = this.lastItem;
			if(lastItem){
				this.hideSub(lastItem);
				this.fireEvent('leave',lastItem);
				this.lastItem = null;
			}
			this.subContainer.setStyle('display', 'none');
		},	
		hideSub: function(item){
			var id = item.getProperty('data-index');
			var subId = this.options['subMenuPrefix'] + id;
			var sub = document.id(subId);
			if(!sub) return;
			sub.setStyle('display','none');
		}
	});	
	
	/*楼层导航开始*/
	ns.ElevatorItem = new Class({
        Implements: [Options,Events],
        options: {
            'index': 0,//第几项
            'container': null,
            'class': 'handler',
            'title-class': 'etitle',
            'cName': ''//中文名称
        },
        initialize: function(options){
            this.setOptions(options);
            var ops = this.options;
            var hd = this.handle = new Element('li', {'class': ops['class']});

            if(ops['container']) hd.inject(document.id(ops['container']));

            new Element('a', {'href': 'javascript:;'}).inject(hd).set('html', (ops['index'] + 1) + 'F');
            new Element('a', {'class': ops['title-class'], 'href': 'javascript:;'}).inject(hd).set('html', ops['cName']);
            this.bounds = {
                'click': this.click.bind(this),
                'over': this.over.bind(this),
                'leave': this.leave.bind(this)
            }
            this.attach();
        },

        click: function(){
            this.fireEvent('click', this.options.index);
        },

        over: function(){
            this.handle.addClass('hover');
        },

        leave: function(){
            this.handle.removeClass('hover');
        },

        attach: function(){
            this.handle.addEvents({
                'click': this.bounds.click,
                'mouseenter': this.bounds.over,
                'mouseleave': this.bounds.leave
            })
        },

        addClass: function(className){
            this.handle.addClass(className);
            return this;
        },

        getSiblings: function(){
            return this.handle.getSiblings();
        },

        inject: function(el){
            this.handle.inject(el);
            return this;
        }
    });
    ns.Elevator = new Class({
        Implements: [Options],
        options: {
            'container': null,/*父容器，如果要直接放到body内可以不填*/
            'floor-class': '.floor',/*楼层的class名称*/
            'class':'elevator',/*楼层控制菜单css名称*/
            'item': {
                'class': 'handler',
                'title-class': 'etitle'
            }
        },

        initialize: function(options){
            this.setOptions(options);
            var ops = this.options;
            var hd = this.handle = new Element('div', {'class': ops['class']}).inject(document.id(ops['container']) || document.body);
            var ul = new Element('ul').inject(hd);
            var floors = this.floors = [];
            this.items = [];
            $$(ops['floor-class']).each(function(item, index){
                floors.push({'item': item, coors: item.getCoordinates()});
            }, this);
            if(floors.length == 0) {
                //alert("没有找到" + ops['floor-class'] + "的楼层数据，请检查传入的楼层css名称！");
			}
            this.bounds = {
                'scroll': this.scroll.bind(this),
                'click': this.click.bind(this),
                'resize': this.resize.bind(this)
            }
            //创建楼层
            floors.each(function(item, index){
				this.items.push(
					new ns.ElevatorItem({
						'class': ops['item']['class'],
						'title-class': ops['item']['title-class'],
						'cName': item['item'].getProperty('data-title'),
						'index': index
					}).inject(ul).addEvent('click', this.bounds.click)
				);
            }, this);

            this.pageWidth = floors[0]['coors']['width'];//根据楼层的宽度取得内容区宽度
            this.ewidth = hd.getWidth()+5;//取得导航的宽度+加5像素间距
            /*计算导航器的top值-居中 round是取整*/
            var floortop = this.floortop = Math.round((window.getHeight() - hd.getCoordinates().height) / 2);

            this.firstFloorTop = floors[0]['coors']['top']-300;
            this.lastFloorTop = floors[floors.length-1]['coors'].bottom;
            this.windowWidth = window.getWidth();
            new ns.SideBy(hd, {'value': floortop});
            this.floorset();
            this.attach();
        },
        attach: function(){
            window.addEvent('scroll', this.bounds.scroll);
            window.addEvent('resize', this.bounds.resize);
        },
        click: function(index){
            new Fx.Scroll(window).toElement(this.floors[index]['item']);
        },
        resize: function(){
            this.floorset();
        },
        scroll: function(){
            this.floorset();
            //if ((document.body.getWidth() - this.pageWidth) / 2 < this.ewidth) return false;
            this.floors.each(function(el,n){
                /*在对象区间时*/
                var handle = this.items[n];
                var coors = el['coors'];
                var item = el['item'];
                var y = window.getScroll().y;
                if (y > (coors.top - this.windowWidth / 5) && y < coors.bottom) {
                    handle.addClass('current').getSiblings().removeClass('current');
                    item.addClass('floor-current');
                } else {
                    item.removeClass('floor-current');
                }
            }, this);
        },
        floorset: function(){
            /*计算导航器的left值*/
            var hd = this.handle;
            var pagewidth = this.pageWidth;
			var scwidth = (window.getWidth() - pagewidth) / 2;
			var eleft = (scwidth - this.ewidth)>0?(scwidth - this.ewidth):0;//left值不能为负，避免被部分隐藏
            hd.setStyles({
                'visibility': 'hidden',
                'left': eleft
            });
			
            //当空白位置足够显示导航器的时候显示它
            if (scwidth >= this.ewidth) {
                hd.setStyle('visibility','visible');
            }

            /*当滚动位置到达第一楼和最后一楼之间时，显示 or 隐藏*/
            var scrollTop = window.getScrollTop();
            hd.setStyle('visibility', (scrollTop <= this.firstFloorTop || scrollTop >= this.lastFloorTop) ? 'hidden':'visible');
        }
    })
	
		
	
	/*自动适应广告的窄屏图切换*/
	ns.imgAuto = function(){
		if (window.getWidth() < 1250) {
			var forInit = $$('img[init_src]');       
			if(!forInit.length) return false;
			var loop = arguments.callee;
			forInit.each(function(item,index){
				if(!item) return;					
				var imginitsrc = item.getProperty('init_src');
				var imginitwidth = item.getProperty('init_width');
				if(imginitwidth){
					item.set('width',imginitwidth).removeProperty('init_width');
				}
				if(imginitsrc){
					item.set('src',imginitsrc).removeProperty('init_src');
				}                 
				//if(index == (forInit.length-1)){loop.delay(200);}			   
			});
		}
	}
	
})(QF);

